<template>
  <div>
    <div class="preview">
      <div
        ref="avatarRef"
        class="pic"
        v-html="value"
        :style="{
          background: bgColor,
          transform: `rotateY(${flipped ? -180 : 0}deg)`,
        }"
        :class="`${bgShape}`"
      ></div>
      <div class="menu">
        <div
          class="g-clickable menu__item"
          :class="{ disable: !prevEnable }"
          @click="$emit('prev')"
        >
          <img src="@/assets/creator/icon/icon-back.svg" />
        </div>
        <div
          class="g-clickable menu__item"
          :class="{ disable: !nextEnable }"
          @click="$emit('next')"
        >
          <img src="@/assets/creator/icon/icon-next.svg" />
        </div>
        <div class="g-clickable menu__item" @click="flipped = !flipped">
          <img src="@/assets/creator/icon/icon-flip.svg" />
        </div>
        <div class="g-clickable menu__item" @click="$emit('random')">
          <img src="@/assets/creator/icon/icon-gen.svg" />
        </div>
        <div class="g-clickable menu__item" @click="download">
          <img src="@/assets/creator/icon/icon-download.svg" />
        </div>
        <div class="g-clickable menu__item" @click="showConfirm">
          <img src="@/assets/creator/icon/icon-nft.svg" />
        </div>
      </div>
      <div class="note">
        <span class="author"
          >Implementation of {{ name }} by {{ author }}.</span
        >
        <span class="license" v-if="license">Licensed under {{ license }}</span>
      </div>
    </div>
    <NouDialog close-on-click-modal :visible.sync="isShowConfirm">
      <Confirm :MetaData="MetaData" @close="isShowConfirm = false" @confirm="confirmMint" />
    </NouDialog>
  </div>
</template>

<script>
import Confirm from "./Confirm";
import NouDialog from "@/components/common/NouDialog";

const NOT_COMPATIBLE_AGENTS = ["quark", "micromessenger", "weibo", "douban"];
import html2canvas from "html2canvas";
import { safeMint } from "@/init";

export default {
  components: {
    Confirm,
    NouDialog,
  },
  props: {
    bgColor: {
      type: String,
      default: "",
    },
    bgShape: {
      type: String,
      default: "",
    },
    value: {
      type: String,
      default: "",
    },
    name: {
      type: String,
      default: "",
    },
    author: {
      type: String,
      default: "",
    },
    license: {
      type: String,
      default: "",
    },
    prevEnable: {
      type: Boolean,
      default: false,
    },
    nextEnable: {
      type: Boolean,
      default: false,
    },
    options: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      flipped: false,
      isShowConfirm: false,
      MetaData: {},
    };
  },
  watch: {
    value() {
      this.change();
    },
  },
  methods: {
    change() {
      this.$nextTick(() => {
        const avatarEle = this.$refs.avatarRef;
        const svg = avatarEle.childNodes[0];
        const g = svg.children[2];
        const { x, y, width, height } = g.getBBox();
        const viewBox = svg
          .getAttribute("viewBox")
          .replace(/^0\s+0\s+/gi, "")
          .split(/\s+/);
        const svgWidth = +viewBox[0];
        const svgHeight = +viewBox[1];
        const move = (svgHeight - height) / 2 - y;
        console.log(
          "change",
          svgWidth,
          svgHeight,
          x,
          y,
          width,
          height,
          `translateY(${move}px)`
        );
        if (height / svgHeight > 0.8) return;
        g.style.transform = `translateY(${move}px)`;
      });
    },
    async download() {
      const avatarEle = this.$refs.avatarRef;
      const userAgent = window.navigator.userAgent.toLowerCase();
      const notCompatible = NOT_COMPATIBLE_AGENTS.some(
        (agent) => userAgent.indexOf(agent) !== -1
      );
      if (avatarEle) {
        const canvas = await html2canvas(avatarEle, {
          backgroundColor: null,
        });
        const dataURL = canvas.toDataURL();

        if (notCompatible) {
          imageDataURL.value = dataURL;
          downloadModalVisible.value = true;
        } else {
          const trigger = document.createElement("a");
          trigger.href = dataURL;
          trigger.download = "token-swap-avatar.png";
          trigger.click();
        }
      }

      recordEvent("click_download", {
        event_category: "click",
      });
    },
    async showConfirm() {
      const properties = {
        bgColor: this.bgColor,
        bgShape: this.bgShape,
      };

      for (var key in this.options) {
        const item = this.options[key];
        properties[key] = (item && item[0]) || "";
      }

      const avatarEle = this.$refs.avatarRef;
      const canvas = await html2canvas(avatarEle, {
        backgroundColor: null,
      });

      this.MetaData = {
        name: this.name,
        description: this.license,
        image: canvas.toDataURL(),
        properties,
      };
      this.isShowConfirm = true;
    },
    async confirmMint(price) {
      setTimeout(() => {
        this.isShowConfirm = false;
      }, 1000);
      const avatarEle = this.$refs.avatarRef;
      const canvas = await html2canvas(avatarEle, {
        backgroundColor: null,
      });
      canvas.toBlob(async (res) => {
        await safeMint(res, this.MetaData, price, () => {
          this.$emit("load");
        });
      });
    },
  },
};
</script>

<style lang="scss">
.preview {
  .pic {
    background: linear-gradient(120deg, rgb(161, 196, 253), rgb(194, 233, 251));
    width: 280px;
    height: 280px;
    border-radius: 25px;
    margin: 0 auto;
    &.circle {
      border-radius: 140px;
      overflow: hidden;
    }
    &.square {
      border-radius: 0;
    }
    &.squircle {
      border-radius: 25px;
      overflow: hidden;
    }
  }

  .menu {
    margin: 60px auto 0;
    padding: 10px 30px;
    border-radius: 30px;
    display: grid;
    grid-gap: 15px;
    grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr;
    align-items: center;
    background-color: #2a2f37;

    &__item {
      width: 42px;
      height: 42px;
      border-radius: 21px;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #404854;

      &.disable {
        cursor: default;
        opacity: 0.6;
      }
    }
  }

  .note {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    margin-top: 20px;

    span {
      font-size: 12px;
      font-family: "Roboto Regular";
      color: var(--note-color);
      line-height: 1.5;
    }
  }
}
</style>
